//
//  MYNewsShopDetailsCalendar.m
//  MuYing
//
//  Created by tbb on 2020/3/7.
//  Copyright © 2020 TBB. All rights reserved.
//

#import "MYNewsShopDetailsCalendar.h"
#import "FSCalendar.h"
#import "RangePickerCell.h"
#import "FSCalendarExtensions.h"

#define kCalendarH 445
#define BGVIEW_TOP (kYQPScreenHeight - kCalendarH)
@interface MYNewsShopDetailsCalendar ()<UIGestureRecognizerDelegate,UICollectionViewDataSource,FSCalendarDataSource,FSCalendarDelegate,FSCalendarDelegateAppearance>

@property (nonatomic, strong) UIView * bgView;
@property (nonatomic, strong) UICollectionView * weekCollView;

@property (nonatomic, strong) NSArray * weekTitleArr;
//回调
@property (nonatomic, copy) SelectDateBlock selectDateBlock;

//calendar
@property (strong, nonatomic) NSCalendar *gregorian;
@property (strong, nonatomic) NSDateFormatter *dateFormatter;
@property (weak, nonatomic) FSCalendar *calendar;
// The start date of the range
@property (strong, nonatomic) NSDate *date1;
// The end date of the range
@property (strong, nonatomic) NSDate *date2;

@property (nonatomic, assign) BOOL allowsMultipleSelection;

- (void)configureCell:(__kindof FSCalendarCell *)cell forDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)position;

@end


@implementation MYNewsShopDetailsCalendar

+ (void)showCalenderViewDate1:(NSDate *)date1 date2:(NSDate *)date2 allowsMultipleSelection:(BOOL)allowsMultipleSelection selectDateBlock:(SelectDateBlock)selectDateBlock {
    MYNewsShopDetailsCalendar *calenderBgView = [[MYNewsShopDetailsCalendar alloc] initWithFrame:[UIScreen mainScreen].bounds];
    calenderBgView.selectDateBlock = selectDateBlock;
    calenderBgView.backgroundColor = HexColorA(0x000000, 0.2);//HexColor(0xF3F5F9);
    [calenderBgView showCalender];
    if (date1) {
        calenderBgView.date1 = date1;
    }
    if (date2) {
        calenderBgView.date2 = date2;
    }

    calenderBgView.allowsMultipleSelection = allowsMultipleSelection;
    calenderBgView.weekTitleArr = @[kYQLS(@"日"),kYQLS(@"一"),kYQLS(@"二"),kYQLS(@"三"),kYQLS(@"四"),kYQLS(@"五"),kYQLS(@"六")];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:calenderBgView action:@selector(cancelCalender)];
    tap.delegate = calenderBgView;
    [calenderBgView addGestureRecognizer:tap];
    
    
    calenderBgView.gregorian = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
    calenderBgView.dateFormatter = [[NSDateFormatter alloc] init];
    calenderBgView.dateFormatter.dateFormat = @"yyyy-MM-dd";
    calenderBgView.calendar.accessibilityIdentifier = @"calendar";
    if (!allowsMultipleSelection) {
        [calenderBgView.calendar selectDate:date1];
    }
}

#pragma mark - FSCalendarDataSource

- (NSDate *)minimumDateForCalendar:(FSCalendar *)calendar
{
    return [NSDate date];//[self.dateFormatter dateFromString:@"2020-01-01"];
}

- (NSDate *)maximumDateForCalendar:(FSCalendar *)calendar
{
    return [self.gregorian dateByAddingUnit:NSCalendarUnitMonth value:10 toDate:[NSDate date] options:0];
}

- (NSString *)calendar:(FSCalendar *)calendar titleForDate:(NSDate *)date
{
    if ([self.gregorian isDateInToday:date]) {
        return kYQLS(@"今天");
    }else{
        if (self.allowsMultipleSelection) {
            NSInteger compare = [NSDate compareOneDay:self.date1 withAnotherDay:self.date2];
            NSString *stateStr = @"";
            if (compare == 1) {
                if (self.date1 == date) {
                    stateStr = kYQLS(@"离店");
                }else if (self.date2 == date){
                    stateStr = kYQLS(@"入住");
                }
            }else if (compare == -1){
                if (self.date1 == date) {
                    stateStr = kYQLS(@"入住");
                }else if (self.date2 == date){
                    stateStr = kYQLS(@"离店");
                }
            }
            return [NSString stringWithFormat:@"%zd\n%@",date.day,stateStr];
        }
    }
    return nil;
}

- (FSCalendarCell *)calendar:(FSCalendar *)calendar cellForDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition
{
    if (self.allowsMultipleSelection) {
        RangePickerCell *cell = [calendar dequeueReusableCellWithIdentifier:@"cell" forDate:date atMonthPosition:monthPosition];
        return cell;
    }
    return nil;
}

- (void)calendar:(FSCalendar *)calendar willDisplayCell:(FSCalendarCell *)cell forDate:(NSDate *)date atMonthPosition: (FSCalendarMonthPosition)monthPosition
{
    if (self.allowsMultipleSelection) {
        [self configureCell:cell forDate:date atMonthPosition:monthPosition];
    }
}

#pragma mark - FSCalendarDelegate

- (BOOL)calendar:(FSCalendar *)calendar shouldSelectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition
{
    return monthPosition == FSCalendarMonthPositionCurrent;
}

- (BOOL)calendar:(FSCalendar *)calendar shouldDeselectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition
{
    return NO;
}

- (void)calendar:(FSCalendar *)calendar didSelectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition
{
    if (self.allowsMultipleSelection) {
        if (calendar.swipeToChooseGesture.state == UIGestureRecognizerStateChanged) {
            // If the selection is caused by swipe gestures
            if (!self.date1) {
                self.date1 = date;
            } else {
                if (self.date2) {
                    [calendar deselectDate:self.date2];
                }
                self.date2 = date;
            }
        } else {
            if (self.date2) {
                [calendar deselectDate:self.date1];
                [calendar deselectDate:self.date2];
                self.date1 = date;
                self.date2 = nil;
            } else if (!self.date1) {
                self.date1 = date;
            } else {
                self.date2 = date;
            }
        }
        [self configureVisibleCells];
        [self.calendar reloadData];
    }else{
        self.date1 = date;
    }
    
    
}

- (void)calendar:(FSCalendar *)calendar didDeselectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition
{
    NSLog(@"did deselect date %@",[self.dateFormatter stringFromDate:date]);
    if (self.allowsMultipleSelection) {
        [self configureVisibleCells];
    }
    
}

- (NSArray<UIColor *> *)calendar:(FSCalendar *)calendar appearance:(FSCalendarAppearance *)appearance eventDefaultColorsForDate:(NSDate *)date
{
    if (self.allowsMultipleSelection) {
        if ([self.gregorian isDateInToday:date]) {
            return @[[UIColor orangeColor]];
        }
        return @[appearance.eventDefaultColor];
    }
    return nil;

}

#pragma mark - Private methods

- (void)configureVisibleCells
{
    [self.calendar.visibleCells enumerateObjectsUsingBlock:^(__kindof FSCalendarCell * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSDate *date = [self.calendar dateForCell:obj];
        FSCalendarMonthPosition position = [self.calendar monthPositionForCell:obj];
        [self configureCell:obj forDate:date atMonthPosition:position];
    }];
}

- (void)configureCell:(__kindof FSCalendarCell *)cell forDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)position
{
    if (self.allowsMultipleSelection) {
        RangePickerCell *rangeCell = cell;
        if (position != FSCalendarMonthPositionCurrent) {
            rangeCell.middleLayer.hidden = YES;
            rangeCell.selectionLayer.hidden = YES;
            return;
        }
        if (self.date1 && self.date2) {
            // The date is in the middle of the range
            BOOL isMiddle = [date compare:self.date1] != [date compare:self.date2];
            rangeCell.middleLayer.hidden = !isMiddle;
        } else {
            rangeCell.middleLayer.hidden = YES;
        }
        BOOL isSelected = NO;
        isSelected |= self.date1 && [self.gregorian isDate:date inSameDayAsDate:self.date1];
        isSelected |= self.date2 && [self.gregorian isDate:date inSameDayAsDate:self.date2];
        rangeCell.selectionLayer.hidden = !isSelected;
    }

}

#pragma mark -- calendar

-(void)showCalender {
    //1. 获取当前应用的主窗口
      UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
      [keyWindow addSubview:self];
      // 浮现动画
      [UIView animateWithDuration:0.3 animations:^{
          //self.selectTableView.left = (kYQPScreenWidth-selectTableViewW);
          self.bgView.top = BGVIEW_TOP-kHeight_Botton_SafeArea;
      }];
}

- (void)cancelCalender {
    
    if (self.selectDateBlock) {
        if (self.allowsMultipleSelection) {
            if (self.date2 && self.date1) {
                NSInteger compare = [NSDate compareOneDay:self.date1 withAnotherDay:self.date2];
                if (compare == 1) {
                    //date1大于date2
                    self.selectDateBlock(self.date2, self.date1);
                }else if (compare == -1){
                    //date2大于date1
                    self.selectDateBlock(self.date1, self.date2);
                }
            }
        }else{
            self.selectDateBlock(self.date1, nil);
        }

    }
    
    // 关闭动画
    [UIView animateWithDuration:0.5 animations:^{
        self.bgView.top = kYQPScreenHeight + kCalendarH;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}
#pragma mark -- UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.weekTitleArr.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    MYNewsShopDetailsCalendarWeekCell *weekCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MYNewsShopDetailsCalendarWeekCell" forIndexPath:indexPath];
    weekCell.titleLb.text = self.weekTitleArr[indexPath.item];
    return weekCell;
}
#pragma mark -- UICollectionViewDataSource end
#pragma mark --lazy

-(FSCalendar *)calendar {
    if (!_calendar) {
        FSCalendar *calendar = [[FSCalendar alloc] initWithFrame:CGRectMake(0, 110, kYQPScreenWidth, 334)];
        calendar.dataSource = self;
        calendar.delegate = self;
        calendar.pagingEnabled = NO;
        calendar.allowsMultipleSelection = self.allowsMultipleSelection;
        calendar.rowHeight = 60;
        calendar.placeholderType = FSCalendarPlaceholderTypeNone;
        [self.bgView addSubview:calendar];
        self.calendar = calendar;
        
        calendar.appearance.titleDefaultColor = [UIColor blackColor];
        calendar.appearance.headerTitleColor = [UIColor blackColor];
        //calendar.appearance.headerDateFormat = @"yyyy MMMM";
        calendar.appearance.headerDateFormat = @"yyyy年M月";
        calendar.appearance.titleFont = [UIFont systemFontOfSize:16];
        calendar.weekdayHeight = 0;
        
        calendar.swipeToChooseGesture.enabled = YES;
        
        calendar.today = nil; // Hide the today circle
        [calendar registerClass:[RangePickerCell class] forCellReuseIdentifier:@"cell"];
        _calendar = calendar;
    }
    return _calendar;
}

-(UIView *)bgView {
if (!_bgView) {
    _bgView = [[UIView alloc] initWithFrame:CGRectMake(0, kYQPScreenHeight+kCalendarH, kYQPScreenWidth, kCalendarH)];
    _bgView.backgroundColor = UIColor.whiteColor;
    [self addSubview:_bgView];
    [UIView roundedSetView:_bgView cornerRadius:12 Type:(kRoundedSetViewTypeTRL)];
    
    UILabel * dateLb = [UILabel new];
    dateLb.text = kYQLS(@"选择日期");
    dateLb.font = [UIFont systemFontOfSize:17 weight:(UIFontWeightMedium)];
    dateLb.textAlignment = NSTextAlignmentCenter;
    dateLb.textColor = kAPPSubTitleColor;
    
    [_bgView addSubview:dateLb];
    [dateLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.top.mas_equalTo(24);
        make.height.mas_equalTo(24);
    }];
    
    UIView *lineView = [UIView new];
    lineView.backgroundColor = HexColor(0xEFEFEF);
    [_bgView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(66);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.height.mas_equalTo(1);
    }];
    
    [_bgView addSubview:self.weekCollView];
    
    }
    return _bgView;
}

-(UICollectionView *)weekCollView {
    if (!_weekCollView) {
        
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        layout.itemSize = CGSizeMake(kYQPScreenWidth / 7.0, 36);
        layout.minimumLineSpacing = 0.001;
        layout.minimumInteritemSpacing = 0.001;
        _weekCollView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 67, kYQPScreenWidth, 36) collectionViewLayout:layout];
        _weekCollView.backgroundColor = UIColor.whiteColor;
        _weekCollView.bounces = NO;
        _weekCollView.showsHorizontalScrollIndicator = NO;
        _weekCollView.dataSource =self;
        [_weekCollView registerNib:[UINib nibWithNibName:@"MYNewsShopDetailsCalendarWeekCell" bundle:nil] forCellWithReuseIdentifier:@"MYNewsShopDetailsCalendarWeekCell"];
    }
    return _weekCollView;
}

#pragma mark --lazy end

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    // 若为UITableViewCellContentView（即点击了tableViewCell），
//    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
//        // cell 不需要响应 父视图的手势，保证didselect 可以正常
//        return NO;
//    }
    
    if (touch.view == self) {
        // cell 不需要响应 父视图的手势，保证didselect 可以正常
        return YES;
    }
    //默认都需要响应
    return  NO;
}
@end
